/**
 * Created with JetBrains WebStorm.
 * User: absir
 * Date: 14-11-11
 * Time: 上午11:57
 * To change this template use File | Settings | File Templates.
 * 有了滑板鞋,天黑都不怕
 */
auiModule.ajaxSubmit = function (form, success, error) {
    var $form = $(form);
    $.ajax({
        type: $form.attr("method") || 'POST',
        url: $form.attr("action"),
        data: $form.serializeArray(),
        dataType: "json",
        cache: false,
        success: success,
        error: error
    });
};

auiModule.iframeSubmit = function (form, callback) {
    var $iframe = auiModule.$iframe;
    if (!$iframe) {
        auiModule.$iframe = $iframe = auiModule.$auiElement.after('<iframe id="auicallbackframe" name="auicallbackframe" src="about:blank" style="display:none"></iframe>').next();
    }

    var $form = $(form);
    if (!form.ajax) {
        $form.append('<input type="hidden" name="ajax" value="1" />');
    }

    form.target = "auicallbackframe";
    var $document = auiModule.$document;
    $document.trigger("ajaxStart");
    $iframe.bind("load", function (event) {
        $iframe.unbind("load");
        $document.trigger("ajaxStop");
        var src = $iframe.attr('src');
        if (src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For Safari
            src == "javascript:'<html></html>';") { // For FF, IE
            return;
        }

        var iframe = $iframe[0];
        var doc = iframe.contentDocument || iframe.document;

        // fixing Opera 9.26,10.00
        if (doc.readyState && doc.readyState != 'complete') return;
        // fixing Opera 9.64
        if (doc.body && doc.body.innerHTML == "false") return;

        var response;
        if (doc.XMLDocument) {
            // response is a xml document Internet Explorer property
            response = doc.XMLDocument;
        } else if (doc.body) {
            try {
                response = $iframe.contents().find("body").text();
                response = jQuery.parseJSON(response);
            } catch (e) { // response is html document or plain text
                response = doc.body.innerHTML;
            }
        } else {
            // response is a xml document
            response = doc;
        }

        callback(response);
    });
};

auiModule.error = function (result) {
    auiModule.instanceComponent(function ($component, $scope) {
        $scope.code = result.code;
        $scope.body = result.body;
        $component.modal().show();
    }, auiModule.tplSrc('error.html'));
};